<template>
  <a-modal
    :width="800"
    :visible="visible"
    title="打标签"
    @cancel="onClose"
    @ok="onSubmit"
    ok-text="确定"
    :destroyOnClose="true"
    :confirmLoading="loading"
  >
    <div class="group-box">
      <template v-for="(item, index) in list" :key="index">
        <div v-show="index <= 4 || (index > 4 && showMore)" class="group-title">{{item.name}}：</div>
        <div v-show="index <= 4 || (index > 4 && showMore)">
          <a-checkable-tag
            v-for="(tag, tagIndex) in item.children"
            :key="tagIndex"
            :checked="selectedTags.findIndex((v) => v.id == tag.id) > -1"
            @change="checked => handleChange(tag, checked)"
          >{{tag.name}}</a-checkable-tag>
          <a-tag color="blue" style="background: #fff; cursor: pointer" @click="handleAddTag(item.id)">
            <PlusOutlined/>
            添加
          </a-tag>
        </div>
      </template>

      <div class="show-more" v-if="list.length > 5 && !showMore" @click.stop="showMore = true">
        更多↓
      </div>

      <a-tag color="blue" style="background: #fff; cursor: pointer; margin-top: 14px;" @click="handleAddGroup">
        <PlusOutlined/>
        新建标签组
      </a-tag>
    </div>


    <!--  新建/编辑-标签-分组  -->
    <EditTags
      :visible="editVisible"
      :editType="editType"
      :currentGroupId="currentGroupId"
      @handleCancel="handleCancel"
      @success="handleEditSuccess"
    />

  </a-modal>
</template>
<script>
import { defineComponent, reactive, toRefs, computed, watch, nextTick } from "vue";
import { message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import {CheckOutlined, PlusOutlined} from "@ant-design/icons-vue";
import EditTags from "@/views/village/BusinessManage/tagModules/EditTags.vue";
import _ from "lodash";

export default defineComponent({
  name: "SelectTagModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    tags: {
      type: Array,
      default: () => [],
    },
    isSave: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {EditTags, PlusOutlined, CheckOutlined},
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      list: [],
      selectedTags: [], // 数组对象形式
      editVisible: false,
      currentGroupId: 0,
      editType: '', // group tag
      showMore: false,
    });


    const onSubmit = () => {
      if (props.isSave) {
        let tagIds = state.selectedTags.map((v) => v.id);
        state.loading = true;
        request
          .put("/org", "/business/customer", {id: props.id, tag_id: tagIds})
          .then((res) => {
            state.loading = false;
            message.success(res?.msg || '保存成功');
            emit('success');
          })
      } else {
        emit('success', _.cloneDeep(state.selectedTags));
      }
    };

    const onClose = () => {
      emit("handleCancel");
    };

    const getTagList = () => {
      request
        .get("/org", "/business/customerTag/index", {})
        .then((res) => {
          state.list = res?.list || [];
        })
    };

    const handleChange = (tag, checked) => {
      const { selectedTags } = state;
      state.selectedTags = checked
        ? [...selectedTags, tag]
        : selectedTags.filter(t => t.id !== tag.id);
    };

    const init = () => {
      state.selectedTags = _.cloneDeep(props.tags);
      getTagList();
    };

    const reset = () => {
      state.loading = false;
      state.list = [];
      state.selectedTags = [];
      state.editVisible = false;
      state.currentGroupId = 0;
      state.editType = '';
      state.showMore = false;
    };

    const handleAddTag = (groupId) => {
      state.currentGroupId = groupId;
      state.editType = 'tag';
      state.editVisible = true;
    };

    const handleAddGroup = () => {
      state.editType = 'group';
      state.editVisible = true;
    };

    const handleCancel = () => {
      state.editVisible = false;
      state.currentGroupId = 0;
      state.editType = '';
    };

    const handleEditSuccess = () => {
      handleCancel();
      getTagList();
    };


    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    return {
      ...toRefs(state),
      onClose,
      onSubmit,
      handleChange,
      handleAddTag,
      handleAddGroup,
      handleCancel,
      handleEditSuccess,
    };
  },
});
</script>

<style lang="less" scoped>
p {
  &:last-of-type {
    margin-bottom: 0;
  }
}
.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}

.group-box {
  max-height: 600px;
  overflow-y: auto;
  width: 100%;
}
.ant-tag-checkable {
  background: #fafafa;
  border: 1px solid #d9d9d9;
}
.ant-tag {
  margin: 4px 8px 4px 0;
}
.show-more {
  width: 100%;
  padding: 6px 0;
  margin-top: 10px;
  text-align: center;
  color: #1890ff;
  cursor: pointer;
}
.group-box {
  .ant-tag-checkable-checked {
    border-color: transparent;
    background-color: #1890ff;
    color: #fff;
  }

  .group-title {
    padding: 6px 0;
    font-size: 14px;
    font-weight: bold;
  }
}


</style>
